package util;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.*;
import java.io.File;
import java.io.FileInputStream;


public class MyFilter extends RGBImageFilter {// 抽象类RGBImageFilter是ImageFilter的子类，

    // 继承它实现图象ARGB的处理

    int alpha = 0;

    static double i=0;

    public MyFilter(int alpha) {// 构造器，用来接收需要过滤图象的尺寸，以及透明度

        this.canFilterIndexColorModel = true;
        this.alpha = alpha;

    }

    @Override
    public int filterRGB(int x, int y, int rgb) {
        i++;
        DirectColorModel dcm = (DirectColorModel) ColorModel.getRGBdefault();

        // DirectColorModel类用来将ARGB值独立分解出来

        int red = dcm.getRed(rgb);

        int green = dcm.getGreen(rgb);

        int blue = dcm.getBlue(rgb);

        int alp=dcm.getAlpha(rgb);
        if((red==255&&blue==255&&green==255)||alp==0){// 如果像素为白色，则让它透明
            alpha = 0;

        }else{

            alpha=255;

        }
        return alpha << 24 | red << 16 | green << 8 | blue;// 进行标准ARGB输出以实现图象过滤

    }

public static void main(String[] args){
    try {

        BufferedImage imageBiao = ImageIO.read(new FileInputStream("e:\\selected.png"));
        Graphics2D g = imageBiao.createGraphics();

        ImageFilter imgf = new MyFilter(255);  //白色

        FilteredImageSource fis = new FilteredImageSource(imageBiao

                .getSource(), imgf);

        Image im = Toolkit.getDefaultToolkit().createImage(fis);

        g.drawImage(im, 0, 0, imageBiao.getWidth(null), imageBiao.getHeight(null), null);

        g.dispose();

        ImageIO.write(imageBiao, "png", new File("e:\\b.png"));

        // 把以上原图和加上图标后的图像



    } catch (Exception e) {

        e.printStackTrace();

    }
}
}